package org.example.index;

import org.apache.paimon.fileindex.FileIndexFormat;
import org.apache.paimon.fileindex.FileIndexReader;
import org.apache.paimon.types.RowType;
import org.apache.paimon.fs.FileIO;
import org.apache.paimon.fs.Path;
import org.apache.paimon.fs.local.LocalFileIO;

import java.io.IOException;
import java.util.Set;

public class PaimonIndexReader {

    public static void main(String[] args) {
        // 指定索引文件的路径
        String indexFilePathStr = "/tmp/paimon/default.db/user_behavior/index/index-0c218a31-7ec8-4fdc-b95d-46e27c501b4d-50";
        Path indexFilePath = new Path(indexFilePathStr);

        // 初始化FileIO实例，假设使用本地文件系统
        FileIO fileIO = new LocalFileIO();

        // 初始化RowType实例，根据实际表结构定义
        RowType rowType = RowType.builder()
                .field("user_id", org.apache.paimon.types.DataTypes.STRING())
                .field("item_id", org.apache.paimon.types.DataTypes.STRING())
                .field("behavior", org.apache.paimon.types.DataTypes.BIGINT())
                .field("dt", org.apache.paimon.types.DataTypes.STRING())
                .field("eventtime", org.apache.paimon.types.DataTypes.TIMESTAMP_LTZ_MILLIS())
                .build();

        try {
            // 创建FileIndexFormat.Reader实例
            System.out.println("Attempting to create FileIndexFormat.Reader...");
            FileIndexFormat.Reader reader = FileIndexFormat.createReader(
                    fileIO.newInputStream(indexFilePath), rowType);

            // 读取指定列的索引信息
            System.out.println("Reading column index...");
            Set<FileIndexReader> readerSet = reader.readColumnIndex("user_id");

            // 打印索引信息
            for (FileIndexReader fileIndexReader : readerSet) {
                System.out.println("Index Reader: " + fileIndexReader);
                // 你可以在这里添加更多的处理逻辑
            }
        } catch (IOException e) {
            System.err.println("IOException occurred: " + e.getMessage());
            e.printStackTrace();
        } catch (RuntimeException e) {
            System.err.println("RuntimeException occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}